package mc0101.mccache.repository;

import lombok.extern.slf4j.Slf4j;
import mc0101.mccache.cache.ZcCacheLocalCache;
import mc0101.mccache.thread.LocalAndRemoteRefreshThread;
import mc0101.mccache.thread.ZcThreadPoolTaskExecutor;
import mc0101.mccache.util.CacheInvalidJudgeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class ZcCacheRepository {

    @Autowired
    private ZcCacheLocalCache zcCacheLocalCache;

    @Autowired
    @Qualifier("ZcCacheThreadPoolTaskExecutorProxy")
    private ZcThreadPoolTaskExecutor threadPoolTaskExecutor;


    @Autowired
    private CacheInvalidJudgeUtils cacheInvalidJudgeUtils;



    /**
     * 根据参数类名获取参数集合
     * @param paramClassName 参数类名
     * @param refreshThread
     * @return 参数集合
     */
    public List<Map<String, Object>> getParamByParamClassName(String paramClassName, LocalAndRemoteRefreshThread refreshThread){
        long begin = System.currentTimeMillis();
        log.debug("开始查询缓存"+paramClassName);
        try {
//            // 判定当前是否超时或者失效了，如果超时或者失效了，内部会刷新缓存的
//            if (cacheInvalidJudgeUtils.isTimeOutAndInvalid()){
//                threadPoolTaskExecutor.execute(refreshThread);
//            }

            return zcCacheLocalCache.getCacheByKey(paramClassName);
        } catch (Exception ex){
            log.error("一级缓存获取参数时异常，可能判定版本时调用redis出现异常，降级为本地定时刷新缓存", ex);
            if(cacheInvalidJudgeUtils.isErrorTimeOut()){
                threadPoolTaskExecutor.execute(refreshThread);
            }
            return zcCacheLocalCache.getCacheByKey(paramClassName);
        } finally {
            log.debug("结束查询缓存"+paramClassName+"，消耗时间为：" + (System.currentTimeMillis() - begin));
        }

    }
}